#include "IOContextPool.h"
#include "../../log.h"

#include <cstddef>

IOContextPool::IOContextPool(uint32_t threads)
:m_works(threads)
,m_contexts(threads)
,m_index(0)
{
    for(uint32_t i = 0; i < threads; ++i)
    {
        m_works[i] = std::unique_ptr<Work>(new Work(m_contexts[i]));
        
        m_threads.emplace_back([this, i](){
            m_contexts[i].run();
        });
    }
}

IOContextPool::IOContext& IOContextPool::GetIOContext()
{
    return m_contexts[m_index++ % m_contexts.size()];
}

void IOContextPool::stop()
{
    for(int i = 0; i < m_threads.size(); ++i)
    {
        m_contexts[i].stop();
        m_works[i].reset();
        m_threads[i].join();
    }
}


IOContextPool& IOContextPool::GetInstance()
{
    static IOContextPool pool;
    return pool;
}